from flask import abort
from flask_sqlalchemy import Pagination
from sqlalchemy import func


def paginate(self, page, per_page=20, error_out=False):
    if error_out and page < 1:
        abort(404)

    total = self.session.execute(
        self.statement.with_only_columns([func.count()]).order_by(None)
    ).scalar()

    if total and total > 0:
        # total = min(100000 * per_page, total)
        # page = min(int(math.ceil(float(total) / float(per_page))), page)
        items = self.limit(per_page).offset((page - 1) * per_page).all()
    else:
        page = 1
        items = []

    return Pagination(self, page, per_page, total, items)
